import sys, os

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import Dispatcher
    from uliweb.orm import Begin, Commit, Rollback

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    try:
        process(args, options, global_options)
        Commit()
    except:
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    print 'Processing org_info or company_info file...'
    if len(args) != 3:
        print "Error, the command line is not right"
        print "     uliweb [options] call import_department [type:ccb|company] dir"
        return
        
    import_(args[2], args[1], options, global_options)
        
def import_(dir, type, options, global_options):
    import csv
    from uliweb.orm import get_model
    from glob import glob
    
    mapping = {
        '1007384':1,
        '1007326':3,
        '1007387':2,
        '1005150':6,
        '1007330':4,
        '1005153':5,
        '010201600':7,
        '0085295533':8,
    }
    
    Department = get_model('department')
    if type == 'ccb':
        _type = '1'
        m = 'org_info'
    else:
        _type = '2'
        m = 'company_info'
    
    c_n = 0
    n_n = 0
    n = 0
    filenames = glob(os.path.join(dir, m+'_*'))
    if len(filenames) > 0:
        filename = filenames[0]
    else:
        filename = None
    if not filename:
        print "Can't find the %s file in %s" % (m, dir)
        return
        
    Department.table.update().execute(delete_flag=True)
    
    for line in csv.reader(open(filename), delimiter='|'):
        code, name = line
        name = unicode(name, 'utf-8')
        code = unicode(code, 'utf-8')
        d = Department.get(Department.c.code==code)
        if d:
            if d.name!=name:
                d.update(name=name, delete_flag=False)
                d.save()
                c_n += 1
                if global_options.verbose:
                    print 'changed', code, name
            else:
                d.delete_flag = False
                d.save()
        else:
            kfzx = mapping.get(code, None)
            d = Department(name=name, code=code, type=_type, delete_flag=False, kfzx=kfzx)
            d.save()
            n_n += 1
            if global_options.verbose:
                print 'added', code, name
        
        n += 1
    os.rename(filename, os.path.join(os.path.dirname(filename), 'bak_' + os.path.basename(filename)))
    print "Total process %d, and added %d, changed %d" % (n, n_n, c_n)